package com.qingcheng.listener;



import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * @author Liu Chengkun
 * @description
 * @date 2019/9/20 0020
 */
public class SqlListener implements ServletContextListener {

    private static String dbHost=null;               // 数据库地址
    private static String dbName=null;                      // 数据库名称
    private static String userName = null;                // 登录名称
    private static String userPassword = null;         // 登录密码
    private static String dbPort=null;                      // 数据库端口号

    public void contextInitialized(ServletContextEvent servletContextEvent) {

        try {
            Connection conn =getMySqlConnection();
            ScriptRunner runner = new ScriptRunner(conn);
            Resources.setCharset(Charset.forName("UTF-8")); //设置字符集,不然中文乱码插入错误
            runner.setLogWriter(null);//设置是否输出日志
            // 绝对路径读取
//          Reader read = new FileReader(new File("f:\\test.sql"));
            // 从class目录下直接读取
            Reader read = Resources.getResourceAsReader("favorite.sql");
            runner.runScript(read);
            runner.closeConnection();
            conn.close();
            System.out.println("sql success.....");
        } catch (Exception e) {
            System.out.println("sql failed......");
            e.printStackTrace();
        }
    }

    /**
     * @功能描述：   获取数据库连接
     *
     * @return
     * @throws Exception
     */
    public  Connection getMySqlConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        InputStream is = SqlListener.class.getClassLoader().getResourceAsStream("db.properties");
        Properties prop = new Properties();
        prop.load(is);
        dbHost = (String) prop.get("dbHost");
        dbName = (String) prop.get("dbName");
        userName = (String) prop.get("userName");
        userPassword = (String) prop.get("userPassword");
        dbPort = (String) prop.get("dbPort");
        String url="jdbc:mysql://"+ SqlListener.dbHost +":"+ SqlListener.dbPort +"/"+ SqlListener.dbName +"?useUnicode=true&characterEncoding=utf-8&port="+ SqlListener.dbPort +"&autoReconnect=true";
        return DriverManager.getConnection(url, SqlListener.userName, SqlListener.userPassword);
    }
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        
    }
}
